<template>
  <div>
    <div class="u2598_account ax_default box_1">
      <div class="u2598_div_account"></div>
    </div>

    <!-- ========================= 详细信息显示位置 ========================== -->
    <div class="container no-padding center" >
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">

        <el-tab-pane label="收货地址" name="receivingAddress">
          <el-table
              :data="addressData"
              style="width: 100%"
              max-height="500"
              :row-class-name="tableRowClassName">
            <el-table-column
                fixed
                prop="receiverName"
                label="收货人"
                width="120">
            </el-table-column>
            <el-table-column
                prop="receiverTel"
                label="手机"
                width="120">
            </el-table-column>
            <el-table-column
                prop="provinceName"
                label="省份"
                width="120">
            </el-table-column>
            <el-table-column
                prop="cityName"
                label="市区"
                width="120">
            </el-table-column>
            <el-table-column
                prop="areaName"
                label="城区"
                width="120">
            </el-table-column>
            <el-table-column
                prop="streetName"
                label="街道"
                width="120">
            </el-table-column>
            <el-table-column
                prop="villageName"
                label="居委会"
                width="150">
            </el-table-column>
            <el-table-column
                prop="detail"
                label="详细地址"
                width=240>
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="120">
              <template slot-scope="scope">
                <el-button
                    @click.native.prevent="editAddress(scope.row)"
                    type="text"
                    size="small">
                  修改
                </el-button>
                <el-button
                    @click.native.prevent="deleteAddress(scope.row)"
                    type="text"
                    size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="新增地址" name="newAddress">
          <div class="account-newadd">
            <el-form label-width="120px" class="form-horizontal mt15">
              <el-form-item label="收货人:">
                <el-input v-model="receiverName" class="form-control"></el-input>
              </el-form-item>

              <el-form-item label="联系电话:">
                <el-input v-model="receiverTel" class="form-control"></el-input>
              </el-form-item>

              <el-form-item>
                <el-select v-model="selectedProvince" placeholder="请选择省份" @click.native="findProvinces">
                  <el-option v-for="province in provinces" :key="province.proviceCode" :label="province.proviceName"
                             :value="province.proviceCode"></el-option>
                </el-select>
                <el-select v-model="selectedCity" placeholder="请选择城市" @click.native="findCities">
                  <el-option v-for="city in cities" :key="city.cityCode" :label="city.cityName"
                             :value="city.cityCode"></el-option>
                </el-select>
                <el-select v-model="selectedCountry" placeholder="请选择区县" @click.native="findAreas">
                  <el-option v-for="country in countries" :key="country.areaCode" :label="country.areaName"
                             :value="country.areaCode"></el-option>
                </el-select>
                <el-select v-model="selectedStreet" placeholder="请选择街道" @click.native="findStreets">
                  <el-option v-for="street in streets" :key="street.streetCode" :label="street.streetName"
                             :value="street.streetCode"></el-option>
                </el-select>
                <el-select v-model="selectedVillage" placeholder="请选择社区" @click.native="findVillages">
                  <el-option v-for="village in villages" :key="village.villagesCode" :label="village.villagesName"
                             :value="village.villagesCode"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="详细地址:">
                <el-input v-model="detailAddress" class="form-control"></el-input>
              </el-form-item>

              <el-checkbox v-model="checked" @click="handleCheckboxClick" style="left: 340px"><h4>设为默认地址</h4></el-checkbox>

              <el-form-item>
                <el-button type="primary" @click="doSubmit">提交</el-button>
                <el-button type="info">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 模态框 - 修改地址 -->
      <el-dialog title="修改地址" :visible.sync="editAddressModalVisible">
        <el-form label-width="120px" class="form-horizontal mt15">
          <el-form-item label="收货人:">
            <el-input v-model="editAddressData.receiverName" class="form-control"></el-input>
          </el-form-item>

          <el-form-item label="联系电话:">
            <el-input v-model="editAddressData.receiverTel" class="form-control"></el-input>
          </el-form-item>

          <el-form-item>
            <el-select v-model="selectedProvince" placeholder="请选择省份" @click.native="findProvinces">
              <el-option v-for="province in provinces" :key="province.proviceCode" :label="province.proviceName"
                         :value="province.proviceCode"></el-option>
            </el-select>
            <el-select v-model="selectedCity" placeholder="请选择城市" @click.native="findCities">
              <el-option v-for="city in cities" :key="city.cityCode" :label="city.cityName"
                         :value="city.cityCode"></el-option>
            </el-select>
            <el-select v-model="selectedCountry" placeholder="请选择区县" @click.native="findAreas">
              <el-option v-for="country in countries" :key="country.areaCode" :label="country.areaName"
                         :value="country.areaCode"></el-option>
            </el-select>
            <el-select v-model="selectedStreet" placeholder="请选择街道" @click.native="findStreets">
              <el-option v-for="street in streets" :key="street.streetCode" :label="street.streetName"
                         :value="street.streetCode"></el-option>
            </el-select>
            <el-select v-model="selectedVillage" placeholder="请选择社区" @click.native="findVillages">
              <el-option v-for="village in villages" :key="village.villagesCode" :label="village.villagesName"
                         :value="village.villagesCode"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址:">
            <el-input v-model="editAddressData.detailAddress" class="form-control"></el-input>
          </el-form-item>

          <el-checkbox v-model="checked" @click="handleCheckboxClick" style="left: 340px"><h4>设为默认地址</h4></el-checkbox>
          

          <el-form-item>
            <el-button type="primary" @click="saveEditAddress">提交</el-button>
            <el-button type="info">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>


    </div>

    <br/><br/><br/><br/>
    <br/><br/><br/><br/>
    <br/><br/><br/><br/>
    <br/><br/><br/><br/>

  </div>
</template>

<script>

import {Message} from "element-ui";

export default {
  name: 'SiteView',
  data() {
    return {
      activeTab: 'receivingAddress',
      session: {
        account: {
          userName: '',
          phoneNumber: '',
          password: ''
        }
      },
      addressData: [],
      editPhoneModalVisible: false,
      newPhoneNumber: '',
      editPasswordModalVisible: false,
      newPassword: '',
      provinces: [],
      cities: [],
      countries: [],
      streets: [],
      villages: [],
      selectedProvince: '',
      selectedCity: '',
      selectedCountry: '',
      selectedStreet: '',
      selectedVillage: '',
      receiverName: '',
      receiverTel: '',
      detailAddress: '',
      editAddressModalVisible: false,
      editAddressData: {},
      defaultAddress: '',
      checked: false,
    };
  },
  methods: {
    handleCheckboxClick() {
      this.checked = true;
    },
    tableRowClassName({row, rowIndex}) {
      console.log(rowIndex);
      if (row.isDefault === 1) {
        return 'warning-row';
      }
      return ''
    },
    handleTabClick(tab) {
      this.activeTab = tab.name;
    },
    showEditPhoneModal() {
      this.editPhoneModalVisible = true;
    },
    showEditPasswordModal() {
      this.editPasswordModalVisible = true;
    },
    findProvinces() {
      this.$axios.get('/address/findProvinces')
          .then(response => {
            this.provinces = response.data.data;
          })
          .catch(error => {
            console.error('获取省份数据出错:', error);
          });
    },
    findCities() {
      this.$axios.get(`/address/findCities/${this.selectedProvince}`)
          .then(response => {
            this.cities = response.data.data;
          })
          .catch(error => {
            console.error('获取城市数据出错:', error);
          });
    },
    findAreas() {
      this.$axios.get(`/address/findAreas/${this.selectedCity}`)
          .then(response => {
            this.countries = response.data.data;
          })
          .catch(error => {
            console.error('获取区县数据出错:', error);
          });
    },
    findStreets() {
      this.$axios.get(`/address/findStreets/${this.selectedCountry}`)
          .then(response => {
            this.streets = response.data.data;
          })
          .catch(error => {
            console.error('获取街道数据出错:', error);
          });
    },
    findVillages() {
      this.$axios.get(`/address/findVillages/${this.selectedStreet}`)
          .then(response => {
            this.villages = response.data.data;
          })
          .catch(error => {
            console.error('获取社区数据出错:', error);
          });
    },
    doSubmit() {
      let url = "/address/addAddress";

      // 对每个字段进行非空判断
      if (this.receiverName === null || this.receiverName === undefined || this.receiverName.trim() === '') {
        Message({
          type: "error",
          message: '收件人姓名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.receiverTel === null || this.receiverTel === undefined || this.receiverTel.trim() === '') {
        Message({
          type: "error",
          message: '收件人电话不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedProvince === null || this.selectedProvince === undefined || this.selectedProvince.trim() === '') {
        Message({
          type: "error",
          message: '省份名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedCity === null || this.selectedCity === undefined || this.selectedCity.trim() === '') {
        Message({
          type: "error",
          message: '城市名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedCountry === null || this.selectedCountry === undefined || this.selectedCountry.trim() === '') {
        Message({
          type: "error",
          message: '地区名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedStreet === null || this.selectedStreet === undefined || this.selectedStreet.trim() === '') {
        Message({
          type: "error",
          message: '街道名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedVillage === null || this.selectedVillage === undefined || this.selectedVillage.trim() === '') {
        Message({
          type: "error",
          message: '社区名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.detailAddress === null || this.detailAddress === undefined || this.detailAddress.trim() === '') {
        Message({
          type: "error",
          message: '详细地址不能为空',
          duration: 1000
        });
        return;
      }

      // 检查电话号码是否小于或等于11位
      if (this.receiverTel && this.receiverTel.length > 11) {
        // 如果电话号码长度超过11位，则显示错误消息
        Message({
          type: "error",
          message: "电话号码长度不能超过11位。",
          duration: 1000
        });
        return; // 停止执行后续代码
      }

      let isDe
      if (this.checked === true) {
        isDe = 1;
      } else {
        isDe = 0;
      }

      let data = {
        "accountId": sessionStorage.getItem("accountId"),
        "receiverName": this.receiverName,
        "receiverTel": this.receiverTel,
        "provinceCode": this.selectedProvince,
        "cityCode": this.selectedCity,
        "areaCode": this.selectedCountry,
        "streetCode": this.selectedStreet,
        "villagesCode": this.selectedVillage,
        "details": this.detailAddress,
        "isDefault": isDe,
      };

      this.$axios.post(url, data)
          .then(response => {
            if (response.data.code === 200) {
              Message({
                type: "success",
                message: response.data.msg,
                duration: 1000
              })
              window.location.reload();
            } else {
              Message({
                type: "error",
                message: response.data.msg,
                duration: 1000
              })
            }
          })
          .catch(error => {
            console.error('添加地址出错:', error);
          });
    },
    editAddress(address) {
      this.editAddressData = {...address};
      // console.log(address)
      this.editAddressModalVisible = true;
    },

    saveEditAddress() {
      let url = '/address/saveEditAddress';

      // 对字段进行非空判断

      if (this.editAddressData.receiverName === null || this.editAddressData.receiverName === undefined || this.editAddressData.receiverName.trim() === '') {
        Message({
          type: "error",
          message: '收件人姓名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.editAddressData.receiverTel === null || this.editAddressData.receiverTel === undefined || this.editAddressData.receiverTel.trim() === '') {
        Message({
          type: "error",
          message: '收件人电话不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedProvince === null || this.selectedProvince === undefined || this.selectedProvince.trim() === '') {
        Message({
          type: "error",
          message: '省份名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedCity === null || this.selectedCity === undefined || this.selectedCity.trim() === '') {
        Message({
          type: "error",
          message: '城市名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedCountry === null || this.selectedCountry === undefined || this.selectedCountry.trim() === '') {
        Message({
          type: "error",
          message: '地区名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedStreet === null || this.selectedStreet === undefined || this.selectedStreet.trim() === '') {
        Message({
          type: "error",
          message: '街道名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.selectedVillage === null || this.selectedVillage === undefined || this.selectedVillage.trim() === '') {
        Message({
          type: "error",
          message: '社区名不能为空',
          duration: 1000
        });
        return;
      }

      if (this.editAddressData.detailAddress === null || this.editAddressData.detailAddress === undefined || this.editAddressData.detailAddress.trim() === '') {
        Message({
          type: "error",
          message: '详细地址不能为空',
          duration: 1000
        });
        return;
      }

      // 检查电话号码是否小于或等于11位
      if ( this.editAddressData.receiverTel &&  this.editAddressData.receiverTel.length > 11) {
        // 如果电话号码长度超过11位，则显示错误消息
        Message({
          type: "error",
          message: "电话号码长度不能超过11位。",
          duration: 1000
        });
        return; // 停止执行后续代码
      }

      let isDe
      if (this.checked === true) {
        isDe = 1;
      } else {
        isDe = 0;
      }

      let data = {
        "addressId": this.editAddressData.addressId,
        "accountId": sessionStorage.getItem("accountId"),
        "receiverName": this.editAddressData.receiverName,
        "receiverTel": this.editAddressData.receiverTel,
        "provinceCode": this.selectedProvince,
        "cityCode": this.selectedCity,
        "areaCode": this.selectedCountry,
        "streetCode": this.selectedStreet,
        "villagesCode": this.selectedVillage,
        "details": this.editAddressData.detailAddress,
        "isDefault": isDe,
      };

      this.$axios.put(url, data)
          .then(response => {
            if (response.data.code === 200) {
              Message({
                type: "success",
                message: response.data.msg,
                duration: 1000
              })
              this.editAddressModalVisible = false;
              window.location.reload();
            } else {
              Message({
                type: "error",
                message: response.data.msg,
                duration: 1000
              })
            }
          })
          .catch(error => {
            console.error('保存修改地址出错:', error);
          });
    },


    deleteAddress(address) {
      this.$axios.post(`/address/deleteAddress/${address.addressId}`)
          .then(response => {
            if (response.data.code === 200) {
              Message({
                type: "success",
                message: response.data.msg,
                duration: 1000
              })
              window.location.reload();
            } else {
              Message({
                type: "error",
                message: response.data.msg,
                duration: 1000
              })
            }
          })
          .catch(error => {
            console.error('删除地址出错:', error);
          });
    },

    /*updateDefaultAddress(address) {
      this.$axios.put(`/address/updateDefaultAddress?id=${address.id}`, {isDefault: address.isDefault})
          .then(response => {
            if (response.data.code === 200) {
              this.defaultAddress = address;
              this.addressData.forEach(item => {
                if (item !== address) {
                  item.isDefault = false;
                }
              });
            } else {
              alert(response.data.msg);
            }
          })
          .catch(error => {
            console.error('更新默认地址出错:', error);
          });
    },*/

    getAddress() {
      let accountId = sessionStorage.getItem("accountId");
      this.$axios.get(`/address/getAddress/${accountId}`)
          .then(res => {
            this.addressData = res.data.data
          })
          .catch(error => {
            console.error('获取地址数据出错:', error);
          });
    }
  },
  created() {
    this.getAddress();
  }
};
</script>

<style scoped>
.container {
  width: 1000px;
  position: absolute;
  top: 20%;
  left: 130%;
}
</style>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>